package com.hex.liyue.lookingdatemodule.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.hex.liyue.R;
import com.hex.liyue.commonmodule.activity.BaseActivity;
import com.hex.liyue.commonmodule.manager.UserManager;
import com.hex.liyue.commonmodule.utils.DateUtils;
import com.hex.liyue.commonmodule.utils.ImageUtils;
import com.hex.liyue.commonmodule.utils.L;
import com.hex.liyue.commonmodule.utils.SexUtils;
import com.hex.liyue.commonmodule.utils.StatusBarCompatUtils;
import com.hex.liyue.commonmodule.utils.T;
import com.hex.liyue.commonmodule.utils.Util;
import com.hex.liyue.commonmodule.view.picker.OptionPicker;
import com.hex.liyue.commonmodule.view.recycleview.YRecycleview;
import com.hex.liyue.giftmodule.activity.GiveAwayGiftsActivity;
import com.hex.liyue.lookingdatemodule.adapter.AdapterPerson;
import com.hex.liyue.lookingdatemodule.bean.AppointmentDetailsResultBean;
import com.hex.liyue.lookingdatemodule.presenter.IInSomeDetailsView;
import com.hex.liyue.lookingdatemodule.presenter.InSomeDetailsPresenter;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.Serializable;
import java.net.URISyntaxException;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 在约详情信息界面
 * Created by WJ on 2016/6/12.
 */
public class InSomeDetailsActivity extends BaseActivity implements IInSomeDetailsView, AdapterPerson.OnItemClickListener {

    @Bind(R.id.tv_toobar_title)
    TextView tvToobarTitle;
    @Bind(R.id.iv_toobar_back)
    ImageView ivToobarBack;
    @Bind(R.id.iv_toobar_right)
    ImageView ivToobarRight;
//    @Bind(R.id.tv_toobar_right)
//    TextView tvToobarRight;

    @Bind(R.id.rl_start_box)
    RelativeLayout rlStartBox;

    @Bind(R.id.vv_video)
    VideoView vvVideo;
    @Bind(R.id.rv_person_list)
    YRecycleview rvPersonList;
    @Bind(R.id.tv_ask_her)
    TextView tvAskHer;
    @Bind(R.id.tv_location)
    TextView tvLocation;
    @Bind(R.id.tv_begin_date)
    TextView tvBeginDate;
    @Bind(R.id.iv_start_video)
    ImageView ivStartVideo;
    @Bind(R.id.iv_avater)
    ImageView ivAvater;
    @Bind(R.id.tv_success_info)
    TextView tvSuccessInfo;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_remark)
    TextView tvRemark;
    @Bind(R.id.tv_want_gifts)
    TextView tvWantGifts;

    private TextView tv_info;
    private MediaController mediaController;
    private InSomeDetailsPresenter iInSomeDetailsPresenter;
    private String appointment_id;//约会ID
    private String uid;//发起约会人的ID
    private AppointmentDetailsResultBean appointmentDetailsResultBeans;
    private double gps_x, gps_y;
    private String location;

    private String appID = "wxbd7b91a516360a2a";
    private String appSecret = "8c51d672ccdc0d6933ef875a4a5b6a2d";
    private IWXAPI wxApi;
    private String avatar;

    @Override
    protected void bindPresenter() {
        iInSomeDetailsPresenter = new InSomeDetailsPresenter(this);
    }

    @Override
    protected void initData(Bundle extras) {
        mediaController = new MediaController(this);
        //VideoView与MediaController进行关联
        vvVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                L.d("WJ", "onCompletion");
                rlStartBox.setVisibility(View.VISIBLE);
                vvVideo.setVisibility(View.GONE);
            }
        });
        vvVideo.setMediaController(mediaController);
        mediaController.setMediaPlayer(vvVideo);
        appointment_id = getIntent().getStringExtra("appointment_id");
        iInSomeDetailsPresenter.requestDetails(appointment_id);

        rvPersonList.setReFreshEnabled(false);
        rvPersonList.setLoadMoreEnabled(false);
        View headView = View.inflate(this, R.layout.head_insome_details, null);
        tv_info = (TextView) headView.findViewById(R.id.tv_info);
        rvPersonList.addHeadView(headView);
        rvPersonList.setLayoutManager(new LinearLayoutManager(this));

        wxApi = WXAPIFactory.createWXAPI(this, "wxbd7b91a516360a2a");
        wxApi.registerApp("wxbd7b91a516360a2a");

    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_in_some_details;
    }

    @Override
    protected void initToolbar() {
        StatusBarCompatUtils.compat(this);
        ivToobarBack.setVisibility(View.VISIBLE);
        ivToobarRight.setVisibility(View.VISIBLE);
        ivToobarRight.setImageResource(R.drawable.icon_more);
    }


    @OnClick({R.id.iv_toobar_back, R.id.tv_ask_her, R.id.iv_toobar_right, R.id.iv_start_video, R.id.tv_success_info})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_toobar_back:
                onBackPressed();
                break;
            case R.id.tv_ask_her:
                //立即约她
                startGiveAwayGiftsActivity();
                break;
            case R.id.iv_toobar_right:
                //关于她
                //弹出选择弹框的界面
                showchoiceDialog();
                // startPersonDetailsActivity();
                break;
            case R.id.tv_success_info:
                //我的应约列表
                startLookingListActivity();
                break;
            case R.id.iv_start_video:
                //播放视频
                ivAvater.setVisibility(View.GONE);
                rlStartBox.setVisibility(View.GONE);
                vvVideo.setVisibility(View.VISIBLE);
                //让VideiView获取焦点
                vvVideo.requestFocus();
                vvVideo.start();
                break;
        }
    }

    /**
     * 展示选择的对话框
     */
    public void showchoiceDialog() {
        AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        //设置对话框的图标
        //builder.setIcon(R.drawable.header);
        //设置对话框的标题
        builder.setTitle("请选择");
        //添加按钮，android.content.DialogInterface.OnClickListener.OnClickListener
        builder.setItems(R.array.lookingdetails, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    Intent intent = new Intent(InSomeDetailsActivity.this, PersonDetailsActivity.class);
                    intent.putExtra("uid", uid);
                    startActivity(intent);
                } else if (which == 1) {
                    //调起百度地图客户端
                    try {
                        Intent intent = Intent.getIntent("intent://map/direction?origin=latlng:" + gps_y + "," + gps_x + "|name:我家&destination=" + location + "&mode=driving®ion=西安&referer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        if (isInstallByread("com.baidu.BaiduMap")) {
                            startActivity(intent); //启动调用
                            L.e("GasStation", "百度地图客户端已经安装");
                        } else {
                            T.show(InSomeDetailsActivity.this, "请先安装百度地图", 0);
                        }
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                } else if (which == 2) {
                    wechatShare(1);
                } else if (which == 3) {
                    Intent intent = new Intent(InSomeDetailsActivity.this, AboutActivity.class);
                    intent.putExtra("uid", uid);
                    intent.putExtra("look", 2 + "");
                    startActivity(intent);
                }
            }
        });
        //创建一个列表对话框
        builder.create().show();
    }

    /**
     * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
     *
     * @param flag (0:分享到微信好友，1：分享到微信朋友圈)
     */
    private void wechatShare(final int flag) {

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://www.liyue888.com/index.php/Home/Share/index?appointment_id=" + appointment_id;
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "把约会玩得这么6，去和ta约一下！ヽ(；▽；)ノ";
        // 这里替换一张自己工程里的图片资源
        BitmapDrawable bmpDraw = (BitmapDrawable) getResources().getDrawable(
                R.drawable.share_icon);
        final Bitmap thumb = bmpDraw.getBitmap();
        if (TextUtils.isEmpty(avatar)) {
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                    : SendMessageToWX.Req.WXSceneTimeline;
            wxApi.sendReq(req);
            return;
        }
        showLod("分享中");
        ImageUtils.getBitmap(avatar, new ImageUtils.ResponseListener() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                closeLod();
                Bitmap bitmap2 = ImageUtils.cQuality(bitmap);
                Bitmap bitmap3 = ImageUtils.zoomImage(bitmap2, 30, 30);
                Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap3, 30, 30, true);
                msg.thumbData = Util.bmpToByteArray(bitmap1, true);
                // msg.setThumbImage(bitmap);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                        : SendMessageToWX.Req.WXSceneTimeline;
                wxApi.sendReq(req);
            }

            @Override
            public void onError() {
                closeLod();
                msg.setThumbImage(thumb);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                        : SendMessageToWX.Req.WXSceneTimeline;
                wxApi.sendReq(req);
            }
        });


    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    @Override
    public void startGiveAwayGiftsActivity() {
        Intent intent = new Intent(this, GiveAwayGiftsActivity.class);
        intent.putExtra("appointment_id", appointment_id);
        intent.putExtra("to_uid", uid);
        startActivity(intent);
        finish();
    }

    @Override
    public void startPersonDetailsActivity() {
        OptionPicker picker = new OptionPicker(this, new String[]{
                "关于ta", "举报"
        });
        picker.setOffset(2);
        picker.setSelectedIndex(1);
        picker.setTextSize(11);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option) {
                if ("关于ta".equals(option)) {
                    Intent intent = new Intent(InSomeDetailsActivity.this, PersonDetailsActivity.class);
                    intent.putExtra("uid", uid);
                    startActivity(intent);
                } else {//举报界面
                    Intent intent = new Intent(InSomeDetailsActivity.this, AboutActivity.class);
                    intent.putExtra("uid", uid);
                    startActivity(intent);
                }
            }
        });
        picker.show();

    }

    @Override
    public void startLookingListActivity() {
        Intent intent = new Intent(this, LookingListActivity.class);
        startActivity(intent);
    }

    @Override
    public void setAdapter(AppointmentDetailsResultBean appointmentDetailsResultBean) {
        appointmentDetailsResultBeans = appointmentDetailsResultBean;
        L.e("appointmentDetailsResultBean", appointmentDetailsResultBean.toString());
        gps_x = Double.parseDouble(appointmentDetailsResultBean.data.gps_x);
        gps_y = Double.parseDouble(appointmentDetailsResultBean.data.gps_y);
        location = appointmentDetailsResultBean.data.location;
        uid = appointmentDetailsResultBean.data.launch_user.uid;
        avatar = appointmentDetailsResultBean.data.launch_user.avatar;
        Glide.with(this).load(appointmentDetailsResultBean.data.launch_user.avatar).centerCrop().error(R.drawable.default_error_image).into(ivAvater);
//        ivAvater.set(appointmentDetailsResultBean.data.launch_user.avatar);
//        tvToobarRight.setText("关于" + SexUtils.getXSex(appointmentDetailsResultBean.data.launch_user.sex));
        tvLocation.setText(appointmentDetailsResultBean.data.event);
        tvAddress.setText(appointmentDetailsResultBean.data.location);
        if (TextUtils.isEmpty(appointmentDetailsResultBean.data.remark)) {
            tvRemark.setText("这个人很懒,什么都没有写");

        } else {
            tvRemark.setText(appointmentDetailsResultBean.data.remark);

        }
        if (null == appointmentDetailsResultBean.data.wanted_gift) {
            tvWantGifts.setVisibility(View.GONE);

        } else {
            tvWantGifts.setText("ta想要:" + appointmentDetailsResultBean.data.wanted_gift.gift_name);
        }
        long time = appointmentDetailsResultBean.data.invitations_time * 1000;
        tvBeginDate.setText(DateUtils.getFormatDate(time, "yyyy年MM月dd日 HH:mm"));
        tvToobarTitle.setText(appointmentDetailsResultBean.data.launch_user.nickname);
        tvAskHer.setText("立即约" + SexUtils.getXSex(appointmentDetailsResultBean.data.launch_user.sex));
        if (appointmentDetailsResultBean.data.is_apply.equals("1")) {
            tvSuccessInfo.setText("预约成功,查看我的应约");
            tvSuccessInfo.setVisibility(View.VISIBLE);
            tvAskHer.setVisibility(View.GONE);
        } else {
            tvSuccessInfo.setVisibility(View.GONE);
            tvAskHer.setVisibility(View.VISIBLE);
        }
        if (appointmentDetailsResultBean.data.launch_user.uid.equals(UserManager.getUserId())) {
            //自己发起的约会
            tvAskHer.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(appointmentDetailsResultBean.data.video)) {
            ivStartVideo.setVisibility(View.GONE);
        } else {
            ivStartVideo.setVisibility(View.VISIBLE);
            vvVideo.setVideoURI(Uri.parse(appointmentDetailsResultBean.data.video));
        }
        if (appointmentDetailsResultBean.data.apply_list.size() > 0) {
            tv_info.setVisibility(View.GONE);
        } else {
            tv_info.setVisibility(View.VISIBLE);
            tv_info.setText("还没有人应约哦~立即约Ta，抢占应约榜黄金骑士！");
        }
//        tv_info.setText("当前" + appointmentDetailsResultBean.data.apply_list.size() + "人应约");
        AdapterPerson adapterPerson = new AdapterPerson(appointmentDetailsResultBean);
        rvPersonList.setAdapter(adapterPerson);
        adapterPerson.setOnItemClickListener(this);
    }

    @Override
    public void onItemClickListener(int position) {
        Intent intent = new Intent(this, CommissionedDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("uid", appointmentDetailsResultBeans.data.apply_list.get(position).uid);
        bundle.putSerializable("gift_list", (Serializable) appointmentDetailsResultBeans.data.apply_list.get(position));
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void showLod(String msg) {
        showLoad(this, msg);
    }

    @Override
    public void closeLod() {
        closeLoad();
    }

    @Override
    public void showT(String msg) {
        showToast(this, msg);
    }

}
